package com.sk.sourcecircle.activity.home.activity;

import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dyhdyh.widget.loading.dialog.LoadingDialog;
import com.sk.sourcecircle.R;
import com.sk.sourcecircle.activity.login.LoginActivity;
import com.sk.sourcecircle.adapter.EventPepAdapter;
import com.sk.sourcecircle.base.BaseActivity;
import com.sk.sourcecircle.callback.HandleDataCallBack;
import com.sk.sourcecircle.callback.MyCallBack;
import com.sk.sourcecircle.dialog.BuyNextDialogFragment;
import com.sk.sourcecircle.dialog.ShareDialogFragment;
import com.sk.sourcecircle.dialog.TipDialogFragment;
import com.sk.sourcecircle.entity.EventDetailsBean;
import com.sk.sourcecircle.utils.AppApi;
import com.sk.sourcecircle.utils.MyUtils;
import com.sk.sourcecircle.utils.SnackUtils;
import com.sk.sourcecircle.view.FixedProportionImageView;
import com.sk.sourcecircle.view.TicketsRadioButton;

import org.sufficientlysecure.htmltextview.HtmlHttpImageGetter;
import org.sufficientlysecure.htmltextview.HtmlTextView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by sk on 2017/11/19.
 */

public class EventDetailsActivity extends BaseActivity implements HandleDataCallBack {
    @BindView(R.id.event_bg)
    FixedProportionImageView eventBg;
    @BindView(R.id.event_name)
    TextView eventName;
    @BindView(R.id.create_time)
    TextView createTime;
    @BindView(R.id.event_time)
    TextView eventTime;
    @BindView(R.id.event_location)
    TextView eventLocation;
    @BindView(R.id.event_pep)
    TextView eventPep;
    @BindView(R.id.event_price)
    TextView eventPrice;
    @BindView(R.id.tv_tip)
    TextView tvTip;
    @BindView(R.id.open_name)
    TextView openName;
    @BindView(R.id.add_care)
    TextView addCare;
    @BindView(R.id.bao_num)
    TextView baoNum;
    @BindView(R.id.more_pep)
    TextView morePep;
    @BindView(R.id.pep_ryc)
    RecyclerView pepRyc;
    @BindView(R.id.html_text)
    HtmlTextView htmlText;
    @BindView(R.id.ask_ll)
    FrameLayout askLl;
    @BindView(R.id.collect)
    FrameLayout collect;
    @BindView(R.id.bao_ming)
    TextView baoMing;
    @BindView(R.id.cancel_care)
    TextView cancelCare;
    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.share)
    ImageView share;

    List<EventDetailsBean.DataBeanX.DataBean> ticketsList = new ArrayList<>();
    ArrayList<EventDetailsBean.DataBeanX.OrderBean> pepList = new ArrayList<>();
    @BindView(R.id.add_collect)
    TextView addCollect;
    @BindView(R.id.cancel_collect)
    TextView cancelCollect;
    private EventDetailsBean eventDetailsBean;

    private int id;
    private LoadingDialog loadingDialog;
    BuyNextDialogFragment buyNextDialogFragment;
    private int num;

    private boolean isNotEnd = false;


    @Override
    protected int getContentView() {
        return R.layout.activity_event_details;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        pepRyc.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        id = getIntent().getIntExtra("id", 0);
        loadingDialog = MyUtils.getLoadingDialog(mContext, false);
        loadingDialog.show();
        AppApi.getEventDetails(id, this, 0, this);

    }

    @TargetApi(Build.VERSION_CODES.M)
    @Override
    public void handlerSuccessData(String result, int tag) {
        loadingDialog.cancelDialog();
        switch (tag) {
            case 0:
                eventDetailsBean = JSON.parseObject(result, EventDetailsBean.class);
                EventDetailsBean.DataBeanX dataBean = eventDetailsBean.getData();
                Glide.with(mContext).load(dataBean.getHead_url()).into(eventBg);

                long applyEndTimeL = eventDetailsBean.getData().getApply_end_time();

                Log.v("applyEndTimeL", applyEndTimeL + "");
                String applyEndTime = MyUtils.timedate(String.valueOf(applyEndTimeL));

                isNotEnd = MyUtils.compareTwoTime("", applyEndTime);

                htmlText.setHtml(dataBean.getContent(), new HtmlHttpImageGetter(htmlText, null, true));

                openName.setText(dataBean.getCommunity_name());
                eventName.setText(dataBean.getName());
                createTime.setText(dataBean.getCreate_time());
                baoNum.setText("已报名（" + dataBean.getNum() + "）");
                eventTime.setText(dataBean.getStart_name() + "至" + dataBean.getEnd_name());
                eventLocation.setText(dataBean.getProvince_name() + dataBean.getCity_name() + dataBean.getDistrict_name() + dataBean.getAddress());
                if (Double.parseDouble(dataBean.getMin_price()) > 0) {
                    eventPrice.setText("¥" + dataBean.getMin_price());
                    eventPrice.setTextColor(Color.parseColor("#ff5050"));
                } else {
                    eventPrice.setText("免费");
                    eventPrice.setTextColor(Color.parseColor("#219021"));
                }
                eventPep.setText("已报名" + dataBean.getNum() + "/" + "限额" + dataBean.getNumAll());
                if (dataBean.getFollow() == 1) {
                    cancelCare.setVisibility(View.VISIBLE);
                    addCare.setVisibility(View.GONE);
                } else {
                    cancelCare.setVisibility(View.GONE);
                    addCare.setVisibility(View.VISIBLE);
                }
                if (dataBean.getFavorites() == 1) {
                    cancelCollect.setVisibility(View.VISIBLE);
                    addCollect.setVisibility(View.GONE);
                } else {
                    cancelCollect.setVisibility(View.GONE);
                    addCollect.setVisibility(View.VISIBLE);
                }
                pepList.clear();
                ticketsList.clear();
                pepList = (ArrayList<EventDetailsBean.DataBeanX.OrderBean>) dataBean.getOrder();
                ticketsList = dataBean.getData();

                EventPepAdapter pepAdapter = new EventPepAdapter(R.layout.item_event_pep, pepList);
                pepRyc.setAdapter(pepAdapter);
                View emptyView = LayoutInflater.from(mContext).inflate(R.layout.empty_pep, pepRyc, false);
                pepAdapter.setEmptyView(emptyView);
                pepAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                        Intent intent = new Intent(mContext, PersonDetailsActivity.class);
                        intent.putExtra("id", pepList.get(position).getUser_id());
                        startActivity(intent);
                    }
                });
                break;
            case 1:
                SnackUtils.show(mRootView, "收藏成功！");
                cancelCollect.setVisibility(View.VISIBLE);
                addCollect.setVisibility(View.GONE);
                break;
            case 2:
                SnackUtils.show(mRootView, "取消收藏成功！");
                cancelCollect.setVisibility(View.GONE);
                addCollect.setVisibility(View.VISIBLE);
                break;
            case 4:
                SnackUtils.show(mRootView, "关注成功！");
                cancelCare.setVisibility(View.VISIBLE);
                addCare.setVisibility(View.GONE);
                break;
            case 10:
                SnackUtils.show(mRootView, "取消关注成功！");
                cancelCare.setVisibility(View.GONE);
                addCare.setVisibility(View.VISIBLE);
                break;
        }
    }

    @Override
    public void handlerFailData(String failString, int tag) {
        loadingDialog.cancelDialog();
    }

    @Override
    public void handleErrorData(String error, int tag) {
        loadingDialog.cancelDialog();
    }

    @OnClick({R.id.add_collect, R.id.cancel_collect, R.id.back, R.id.share, R.id.location_ll, R.id.add_care, R.id.cancel_care, R.id.more_pep, R.id.ask_ll, R.id.bao_ming, R.id.open_name})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.share:
                String summary = String.valueOf(Html.fromHtml(eventDetailsBean.getData().getContent(), null, null));
                ShareDialogFragment shareDialogFragment = new ShareDialogFragment();
                shareDialogFragment.setImageUrl(eventDetailsBean.getData().getHead_url());
                shareDialogFragment.setSummary(summary);
                shareDialogFragment.setTitle(eventDetailsBean.getData().getName());
                shareDialogFragment.setActivityShare(id + "&1");
                shareDialogFragment.setTargetUrl("https://appdev.qigle.com/yuanquan/share/share/getActivity?id=" + eventDetailsBean.getData().getActivity_id());
                shareDialogFragment.show(getFragmentManager(), "share");
                break;
            case R.id.location_ll:
                if (eventDetailsBean.getData().getLat() != null && eventDetailsBean.getData().getLat().length() > 0 && eventDetailsBean.getData().getLng() != null && eventDetailsBean.getData().getLng().length() > 0) {
                    double lat = Double.parseDouble(eventDetailsBean.getData().getLat());
                    double lng = Double.parseDouble(eventDetailsBean.getData().getLng());
                    Intent intent = new Intent(mContext, MapActivity.class);
                    intent.putExtra("lat", lat);
                    intent.putExtra("lng", lng);
                    intent.putExtra("area", eventDetailsBean.getData().getCity_name() + eventDetailsBean.getData().getDistrict_name() + eventDetailsBean.getData().getAddress());
                    startActivity(intent);
                } else {
                    SnackUtils.showError(mRootView, "尚未定位到该活动的坐标！");
                }
                break;
            case R.id.add_care:

                if (MyUtils.getToken(mContext) != null && MyUtils.getToken(mContext).length() == 0) {
                    Toast.makeText(mContext, "您尚未登陆，请先登录！", Toast.LENGTH_SHORT).show();
                    Intent loginIntent = new Intent(mContext, LoginActivity.class);
                    startActivityForResult(loginIntent, 100);
                    return;
                }
                loadingDialog.show();
                AppApi.addCareGroup(eventDetailsBean.getData().getCommunity_id(), EventDetailsActivity.this, 4, EventDetailsActivity.this);

                break;
            case R.id.cancel_care:
                if (MyUtils.getToken(mContext) != null && MyUtils.getToken(mContext).length() == 0) {
                    Toast.makeText(mContext, "您尚未登陆，请先登录！", Toast.LENGTH_SHORT).show();
                    Intent loginIntent = new Intent(mContext, LoginActivity.class);
                    startActivityForResult(loginIntent, 100);
                    return;
                }
                TipDialogFragment tipDialogFragment = new TipDialogFragment();
                tipDialogFragment.setContent("确认取消关注此社群？");
                tipDialogFragment.setMyCallBack(new MyCallBack() {
                    @Override
                    public void releaseAlbum() {

                    }

                    @Override
                    public void joinGroup() {

                    }

                    @Override
                    public void takePhoto() {

                    }

                    @Override
                    public void choosePhoto() {

                    }

                    @Override
                    public void sure() {
                        loadingDialog.show();
                        AppApi.cancelCareGroup(eventDetailsBean.getData().getCommunity_id(), EventDetailsActivity.this, 10, EventDetailsActivity.this);
                    }

                    @Override
                    public void cancelOder(String string) {

                    }

                    @Override
                    public void chooseGroup(String id) {

                    }

                    @Override
                    public void cancel() {

                    }

                    @Override
                    public void sendText(String comment) {

                    }
                });
                tipDialogFragment.show(getSupportFragmentManager(), "tip");
                break;
            case R.id.more_pep:
                Intent pepIntent = new Intent(mContext, MoreJoinedActivity.class);
                pepIntent.putParcelableArrayListExtra("data", pepList);
                startActivity(pepIntent);
                break;
            case R.id.ask_ll:

                if (MyUtils.getToken(mContext) != null && MyUtils.getToken(mContext).length() == 0) {
                    Toast.makeText(mContext, "您尚未登陆，请先登录！", Toast.LENGTH_SHORT).show();
                    Intent loginIntent = new Intent(mContext, LoginActivity.class);
                    startActivityForResult(loginIntent, 100);
                    return;
                }

                if (eventDetailsBean.getData().getHx_login() != null) {
                    Intent chantIntent = new Intent(mContext, ChatActivity.class);
                    String username = eventDetailsBean.getData().getHx_login();
                    Log.v("username", username);
                    // it's single chat
                    chantIntent.putExtra("id", username);
                    chantIntent.putExtra("toName", eventDetailsBean.getData().getCommunity_user().getNickname());
                    chantIntent.putExtra("toUrl", eventDetailsBean.getData().getCommunity_user().getHead_url());
                    chantIntent.putExtra("toId", eventDetailsBean.getData().getCommunity_user().getUser_id());
                    startActivity(chantIntent);
                } else {
                    SnackUtils.showError(mRootView, "该商家暂无联系账号！");
                }

                break;
            case R.id.add_collect:

                if (MyUtils.getToken(mContext) != null && MyUtils.getToken(mContext).length() == 0) {
                    Toast.makeText(mContext, "您尚未登陆，请先登录！", Toast.LENGTH_SHORT).show();
                    Intent loginIntent = new Intent(mContext, LoginActivity.class);
                    startActivityForResult(loginIntent, 100);
                    return;
                }

                loadingDialog.show();
                AppApi.addCollect(id, 1, EventDetailsActivity.this, 1, EventDetailsActivity.this);
                break;
            case R.id.cancel_collect:

                if (MyUtils.getToken(mContext) != null && MyUtils.getToken(mContext).length() == 0) {
                    Toast.makeText(mContext, "您尚未登陆，请先登录！", Toast.LENGTH_SHORT).show();
                    Intent loginIntent = new Intent(mContext, LoginActivity.class);
                    startActivityForResult(loginIntent, 100);
                    return;
                }

                loadingDialog.show();
                AppApi.cancelCollect(id, 1, EventDetailsActivity.this, 2, EventDetailsActivity.this);
                break;
            case R.id.bao_ming:

                if (MyUtils.getToken(mContext) != null && MyUtils.getToken(mContext).length() == 0) {
                    Toast.makeText(mContext, "您尚未登陆，请先登录！", Toast.LENGTH_SHORT).show();
                    Intent loginIntent = new Intent(mContext, LoginActivity.class);
                    startActivityForResult(loginIntent, 100);
                    return;
                }

                if (isNotEnd) {
                    buyNextDialogFragment = new BuyNextDialogFragment();
                    buyNextDialogFragment.setDataBeanList(ticketsList);
                    buyNextDialogFragment.setMyCallBack(EventDetailsActivity.this);
                    buyNextDialogFragment.show(getFragmentManager(), "show");
                } else {
                    SnackUtils.show(mRootView, "该活动报名时间已经截止!");
                }

                break;

            case R.id.open_name:
                Intent groupIntent = new Intent(mContext, GroupDetailsActivity.class);
                groupIntent.putExtra("id", eventDetailsBean.getData().getCommunity_id());
                startActivity(groupIntent);
                break;

        }
    }

    @Override
    public void sure() {
        super.sure();

        TicketsRadioButton ticketsRadioButton = buyNextDialogFragment.getCheckedButton();
        if (ticketsRadioButton != null) {
            EventDetailsBean.DataBeanX.DataBean dataBean = (EventDetailsBean.DataBeanX.DataBean) ticketsRadioButton.getTag();
            double total = buyNextDialogFragment.getTotal();
            int num = buyNextDialogFragment.getNum();
            if (MyUtils.getPhone(mContext) != null && MyUtils.getPhone(mContext).length() > 0 && MyUtils.getName(mContext) != null && MyUtils.getName(mContext).length() > 0) {
                Intent intent = new Intent(mContext, ConfirmMessageWithInfoAct.class);
                intent.putExtra("data", eventDetailsBean.getData());
                intent.putExtra("ticket", dataBean);
                intent.putExtra("total", total);
                intent.putExtra("num", num);
                startActivity(intent);
            } else {
                Intent intent = new Intent(mContext, ConfirmMessageActivity.class);
                intent.putExtra("data", eventDetailsBean.getData());
                intent.putExtra("ticket", dataBean);
                intent.putExtra("total", total);
                intent.putExtra("num", num);
                startActivity(intent);
            }
        } else {
            SnackUtils.showError(mRootView, "请选择您需要购买的票种!");
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == -1) {
            if (requestCode == 100) {
                loadingDialog.show();
                AppApi.getEventDetails(id, this, 0, this);
            }
        }
    }

}
